/*
 * @Descripttion: 护士给医生出库
 * @version: 1.0
 * @Author: 自由如风
 * @Date: 2021-04-28 12:23:35
 * @LastEditors: 自由如风
 * @LastEditTime: 2021-04-28 14:44:39
 */

const DB = require("../../lib/DB");
const { Success } = require("../../lib/Response");

module.exports = async function (ctx, next) {

    // 开启事务
    const t = await DB.transaction();
    try {
        const medicine_lib = await DB.models.medicine_lib.findByPk(ctx.request.body.medicine_lib_id, { transaction: t });


        if (medicine_lib.amount < ctx.request.body.out_amount) {
            throw new Error("数量不足")
        }
        medicine_lib.amount -= ctx.request.body.out_amount;
        await medicine_lib.save({ transaction: t })


        await DB.models.doctor_medicine_lib.create({
            medicine_lib_id: ctx.request.body.medicine_lib_id,
            out_time: Date.now(),
            amount: medicine_lib.amount,
            out_amount: ctx.request.body.out_amount,
            conservator: ctx.session.user.id,
            doctor: ctx.request.body.doctor,
            memo: ctx.request.body.memo,
        }, { transaction: t })

        await t.commit()
        ctx.body = new Success()
        await next();

    } catch (e) {
        await t.rollback();
        throw e;
    }
}